package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OederTask {
    @Autowired
    private OrderMapper orderMapper;
    //定时处理超时订单
    @Scheduled(cron = "0 * * * * ?") // 每分钟触发一次
    public void handleTimeOrder(){
        log.info("定时处理超时订单", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders >list = orderMapper.selectByStatusAndTime(Orders.PENDING_PAYMENT,time);
        if(list != null && list.size() > 0) {
            for (Orders order : list) {
                order.setStatus(Orders.CANCELLED); // 更新取消状态
                order.setCancelReason("超时未支付");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    //定时清空派送订单
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点触发一次
    public void handleDeliveryOrder(){
        log.info("定时清空派送订单", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders >list = orderMapper.selectByStatusAndTime(Orders.DELIVERY_IN_PROGRESS,time);
        if(list != null && list.size() > 0) {
            for (Orders order : list) {
                order.setStatus(Orders.COMPLETED); // 更新取消状态
                orderMapper.update(order);
            }
        }
    }
}
